<?php

namespace Houdunwang\Mini;

use Exception;

abstract class Mini
{
    protected $api = 'https://api.weixin.qq.com';

    //配置
    protected static $config;

    /**
     * 初始化服务
     * @param mixed $config
     * @return static
     */
    public static function init($config)
    {
        $instance = new static();
        $instance->config($config);
        return $instance;
    }

    /**
     * 微信配置
     * @param mixed $data
     * @return mixed
     */
    public function config($data = null)
    {
        if (is_string($data)) {
            return self::$config[$data] ?? null;
        } else if (is_null($data)) {
            return self::$config;
        } else {
            self::$config = $data;
        }

        return $this;
    }

    /**
     * 微信返回消息格式化
     * @param mixed $response
     * @return mixed
     * @throws Exception
     */
    protected function return($response)
    {
        $errors = [];
        if (isset($response['errcode']) && $response['errcode'] != 0) {
            throw new Exception($errors[$response['errcode']] ?? $response['errmsg']);
        }
        return $response;
    }
}
